#!/usr/bin/env python

import os
import sys
import locale

from optparse import OptionParser

import collate

def main(argv):
    lines = []
    encoding = locale.getpreferredencoding()
    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error:
        pass

    parser = OptionParser()
    parser.add_option("-b", "--backend", dest="backend",
                      help="use backend BACKEND", metavar="BACKEND",
                      default="default")
    parser.add_option("-l", "--locale", dest="locale",
                      help="use locale LOCALE", metavar="LOCALE",
                      default=locale.getlocale()[0])
    parser.add_option("-e", "--encoding", dest="encoding",
                      help="use encoding ENCODING", metavar="ENCODING",
                      default=encoding)
    parser.add_option("-d", "--diagnostics", action="store_true",
                      dest="diagnostics", help="print diagnostic information")

    options, args = parser.parse_args()

    if options.backend or options.locale or options.encoding:
        backend = getattr(collate, options.backend)
        collate.set_collator(backend, options.locale, options.encoding)

    if options.diagnostics:
        print >>sys.stderr, "Backend: " + collate.default.__name__
        print >>sys.stderr, "Locale: " + collate.collator.locale
        print >>sys.stderr, "Encoding: " + collate.collator.encoding

        if not args:
            raise SystemExit

    if not args:
	args.append("-")
    for filename in args:
	if filename == "-":
	    fileobj = sys.stdin
	else:
	    fileobj = open(filename, "rU")
	for line in fileobj:
	    line = line.strip()
	    line = line.decode(encoding, "replace")
	    lines.append(line)
    lines.sort(key=collate.key)

    for line in lines:
	print line.encode(encoding, "replace")

if __name__ == "__main__":
    main(sys.argv[1:])
